package com.ruyuan.seckill.service.cartbuilder.impl;


import com.ruyuan.seckill.domain.Buyer;
import com.ruyuan.seckill.domain.vo.CartSkuVO;
import com.ruyuan.seckill.domain.vo.CartVO;
import com.ruyuan.seckill.domain.vo.PriceDetailVO;
import com.ruyuan.seckill.service.cartbuilder.CartPriceCalculator;
import com.ruyuan.seckill.utils.CurrencyUtil;
import com.ruyuan.seckill.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class PintuanCartPriceCalculatorImpl implements CartPriceCalculator {



    @Override
    public PriceDetailVO countPrice(List<CartVO> cartList, Boolean includeCoupon) {

        //根据规则计算价格
        PriceDetailVO priceDetailVO = this.countPriceWithRule(cartList);


        return priceDetailVO;
    }

    @Override
    public PriceDetailVO countPrice(List<CartVO> cartList, Buyer buyer, Boolean includeCoupon) {
        //根据规则计算价格
        PriceDetailVO priceDetailVO = this.countPriceWithRule(cartList);


        return priceDetailVO;
    }

    private PriceDetailVO countPriceWithRule(List<CartVO> cartList) {

        PriceDetailVO price = new PriceDetailVO();

        for (CartVO cart : cartList) {


            PriceDetailVO cartPrice = new PriceDetailVO();
            cartPrice.setFreightPrice(cart.getPrice().getFreightPrice());
            for (CartSkuVO cartSku : cart.getSkuList()) {


                //购物车全部商品的原价合
                cartPrice.setOriginalPrice(CurrencyUtil.add(cartPrice.getGoodsPrice(), cartSku.getSubtotal()));

                //购物车所有小计合
                cartPrice.setGoodsPrice(CurrencyUtil.add(cartPrice.getGoodsPrice(), cartSku.getSubtotal()));

                //累计商品重量
                double weight = CurrencyUtil.mul(cartSku.getGoodsWeight(), cartSku.getNum());
                double cartWeight = CurrencyUtil.add(cart.getWeight(), weight);
                cart.setWeight(cartWeight);


            }


            //总价为商品价加运费
            double totalPrice = CurrencyUtil.add(cartPrice.getGoodsPrice(), cartPrice.getFreightPrice());
            cartPrice.setTotalPrice(totalPrice);
            cart.setPrice(cartPrice);

            price = price.plus(cartPrice);


        }


        log.debug("计算完优惠后购物车数据为{}", JsonUtil.objectToJson(cartList));

        log.debug("价格为：{}",price);

        return price;
    }


}
